<template>
	<div class="login">
		<template v-if="showInput">
			<van-image :src="require('./image/logo.png')" />
			<h3>村民经营性自建房消防安全排查治理</h3>
			<div class="input-box">
				<input
					type="text"
					v-model="echoData.countyName"
					placeholder="请选择行政区"
					readonly
					@click="changeRegion('county')"
				/>
				<van-icon name="arrow" />
			</div>
			<div class="input-box">
				<input
					type="text"
					v-model="echoData.townshipName"
					placeholder="请选择镇街"
					readonly
					@click="changeRegion('township')"
				/>
				<van-icon name="arrow" />
			</div>
			<!-- <div class="input-box" v-if="route.query.orgCode?.length === 12 && ['检查员'].includes(route.query.roleName)">
				<input
					type="text"
					v-model="echoData.villageName"
					placeholder="请选择村"
					readonly
					@click="changeRegion('village')"
				/>
				<van-icon name="arrow" />
			</div> -->
			<div class="input-box" >
				<input
					type="text"
					v-model="echoData.villageName"
					placeholder="请选择村"
					readonly
					@click="changeRegion('village')"
				/>
				<van-icon name="arrow" />
			</div>
			<div class="input-box">
				<input
					type="text"
					v-model="filterData.name"
					placeholder="请输入姓名"
				/>
			</div>
			<div class="btn">
				<van-button
					block
					type="primary"
					@click="login"
				>
					登录
				</van-button>
				<van-button
					block
					@click="router.back()"
				>
					退出
				</van-button>
			</div>
		</template>
    
    <component
      :is="phonePopup"
    />

		<van-popup v-model:show="echoData.regionVisible" position="bottom" round>
			<van-picker
				:columns="echoData[echoData.regionType]"
				@confirm="onConfirm"
				@cancel="echoData.regionVisible = false"
			/>
		</van-popup>
	</div>
</template>

<script setup>
import { ref, nextTick, onMounted, reactive, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { userLogin, loginInfoConfirm, getRegion, regionmsg } from '@/service/village'
import { useUserStore, useLoginStore } from '@/store'
import { Toast } from 'vant'
import phonePopup from '@/components/phonePopup.vue'

const userStore = useUserStore()
const loginStore = useLoginStore()

const route = useRoute()
const router = useRouter()

const showInput = ref(false)
const filterData = reactive({
	xzqdm: '',
	towndm: '',
	villagedm: '',
	name: ''
})

const echoData = reactive({
	visible: true,
	regionVisible: false,
	regionType: 'county',
	countyName: '',
	county: [],
	townshipName: '',
	township: [],
	villageName: '',
	village: []
})

const onConfirm = val => {
	echoData.regionVisible = false
	if (echoData.regionType === 'county') {
		echoData.countyName = val?.regionName
		filterData.xzqdm = val?.regionCode
		echoData.townshipName = ''
		filterData.towndm = ''
		echoData.villageName = ''
		filterData.villagedm = ''
		getRegionData(val?.regionCode, 'township')
	} else if (echoData.regionType === 'township') {
		echoData.townshipName = val?.regionName
		filterData.towndm = val?.regionCode
		echoData.villageName = ''
		filterData.villagedm = ''
		getRegionData(val?.regionCode, 'village')
	} else if (echoData.regionType === 'village') {
		echoData.villageName = val?.regionName
		filterData.villagedm = val?.regionCode
	}
}

const getRegionData = async (id, type) => {
	const result = await getRegion({
		parentid: id
	})
	if (result?.succ) {
		echoData[type] = result?.data?.map(item => {
			return {
				text: item.regionName,
				...item
			}
		})
	}
}

const changeRegion = type => {
	const roleEnum = {
		'委办局管理员': ['county', 'township', 'village'],
		'市级管理员': ['county', 'township', 'village'],
		'区级管理员': ['township', 'village'],
		'检查员': ['village'],
    '街道管理员': ['village'],
	}
	if (roleEnum[route.query.roleName].includes(type)) {
		echoData.regionType = type
		nextTick(() => {
			echoData.regionVisible = true
		})
	}
}

const login = async () => {
	if (!filterData.xzqdm) {
		Toast('请先选择行政区划')
		return
	}
	if (!filterData.name) {
		Toast('请输入用户名')
		return
	}
	if (route.query.orgCode?.length === 12 && !filterData.villagedm && route.query.roleName === '检查员') {
		Toast('请选择村')
		return
	}

	try {
		const result = await loginInfoConfirm({
			regioncode: filterData.villagedm || filterData.towndm || filterData.xzqdm,
			name: filterData.name,
			id: route.query.id
		})
		if (result?.succ) {
			ssoLogin()
		}
	} catch (e) {

	}
}

const ssoLogin = async () => {
	try {
		const result = await userLogin({
			id: route.query.id,
		})
		if (result.succ) {
			userStore.setUserInfo({
        ...result?.data,
        qaaId: route.query.id,
      })
			localStorage.setItem(process.env.VUE_APP_TOKEN_NAME, result?.data?.jwtToken)
			await loginStore.setLoginInfo()
			nextTick(() => {
				router.replace({
					name: 'menu',
				})
			})
		} else {
			throw new Error(result)
		}
	} catch (e) {
		if (['市级管理员', '区级管理员', '委办局管理员'].includes(route.query.roleName)) {
			ssoLoginCity()
		} if (route.query.roleName === '检查员' && !([9, 12].includes(route.query.orgCode?.length))) {
			ssoLoginCity()
		} else {
			showInput.value = true
			getRegionData(route.query.orgCode, 'village')
			getRegionByQuery()
		}
	}
}

const getRegionByQuery = async () => {
	const result = await regionmsg({
		code: route.query.orgCode
	})
	filterData.xzqdm = result?.data?.[0]?.xzqdm
	filterData.towndm = result?.data?.[0]?.towndm
	filterData.villagedm = result?.data?.[0]?.villagedm

	echoData.countyName = result?.data?.[0]?.xzq
	echoData.townshipName = result?.data?.[0]?.town
	echoData.villageName = result?.data?.[0]?.village
}

const ssoLoginCity = async () => {
	try {
		const result = await loginInfoConfirm({
			regioncode: route.query.orgCode,
			id: route.query.id,
		})
		if (result?.succ) {
			ssoLogin()
		}
	} catch (e) {

	}
}

watch(() => route.query, () => {
	if (route.query.orgCode?.length === 12 && route.query.orgCode?.substr(9) === '000') {
		router.replace({
			name: route.name,
			query: {
				...route.query,
				orgCode: route.query.orgCode?.substr(0, 9)
			}
		})
	} else {
		ssoLogin()
	}
}, { immediate: true, deep: true })
</script>

<style scoped lang="less">
.login {
	height: 100%;
	background: url(image/page_bg.png) no-repeat top center / 100% 100%;
	display: flex;
	flex-direction: column;
	align-items: center;
	.tel {
		position: fixed;
		bottom: 32px;
    color: #fff;
	}
	.van-image {
		width: 146px;
		margin-bottom: 24px;
		margin-top: 100px;
	}
	h3 {
		color: #fff;
		margin-bottom: 86px;
	}
	.input-box {
		position: relative;
		width: 630px;
		height: 92px;
		margin-bottom: 48px;
		input {
			width: 100%;
			height: 100%;
			border-radius: 16px;
			font-size: 32px;
			text-indent: 28px;
			&::placeholder {
				color: #AAABAD;
			}
		}
		i {
			position: absolute;
			top: 50%;
			transform: translateY(-50%);
			right: 24px;
			width: 32px;
			height: 32px;
			opacity: .3;
		}
		.list {
			width: 100%;
			position: absolute;
			top: 120px;
			background: #fff;
			z-index: 200;
			box-sizing: border-box;
			padding: 20px 32px;
			max-height: 45vh;
			overflow: auto;
			.item {
				padding: 12px 0;
				border-bottom: 2px solid var(--border-color);
				min-height: 44px;
				line-height: 44px;
			}
		}
	}
	.btn {
		display: flex;
		gap: 24px;
		width: 630px;
	}
}
</style>
